import { BizKfExtraProColumnType } from '@/components';
import * as API from '@/services';
import { Divider, message, Space, Typography } from 'antd';
import { CommonRegex, KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, useBackendEnum } from 'kf-web-library';
import React, { useRef, useState } from 'react';
import { useLocation, useAccess, Link, history } from 'umi';
import QuickForm from './components/QuickForm';
import defaultPlaceHolderImg from '@/assets/default_placeholder.png';
import { CheckCircleOutlined, EditOutlined, RocketOutlined } from '@ant-design/icons';
import './index.less';
import { useUpdateEffect } from 'ahooks';
import queryString from 'query-string';

type Entity = API.Journal;
type EntityPageQueryParams = API.RolePageQueryParams;
const entityTypeName = '期刊';
const EntityQuickForm = QuickForm;

interface EntityTableListProps {}

/**
 * 期刊 列表页面
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const access = useAccess();
  const { enumDict, enumTypeDict, getBackendEnum } = useBackendEnum();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const [languageType, setLanguageType] = useState<string>('CN');

  useUpdateEffect(() => {
    actionRef.current?.reload();
  }, [languageType]);

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(p) => {
        return API.queryJournals({ ...p, languageType });
      }}
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.id as string, () => {
              API.deleteJournal(record.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
        multi: {
          deleteMultiple: (records) => {
            KfModal.batchActionConfirm('删除', records.length, () => {
              API.deleteJournals(records.map((r) => r.id!)).then((res) => {
                if (res.flag) {
                  message.info('批量删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: {
            show: true,
            buttonText: '新增',
            fltRender: () => ({
              title: `新建`,
              content: <EntityQuickForm formType={'create'} />,
            }),
          },
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑`,
            width: 900,
            content: <EntityQuickForm formType={'modify'} bizId={record.id} />,
          }),
          viewModal: (record) => ({
            fltType: 'modal',
            title: `查看`,
            width: 900,
            content: <EntityQuickForm formType={'view'} bizId={record.id} />,
          }),
        },
      }}
      proTable={{
        tableBarActions: (action, rows) => {
          return [];
        },
        search: {
          optionRender: (searchConfig, formProps, dom) => [...dom],
        },
        toolbar: {
          menu: {
            type: 'tab',
            activeKey: languageType,
            items: [
              {
                key: 'CN',
                label: <span>中文刊</span>,
              },
              {
                key: 'EN',
                label: <span>英文刊</span>,
              },
            ],
            onChange: (key) => {
              setLanguageType(key as string);
            },
          },
        },
      }}
      columns={[
        {
          title: '关键字',
          dataIndex: 'searchText',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          fieldProps: {
            placeholder: '关键字',
          },
        },
        {
          title: '序号',
          width: 50,
          key: '_seq_index_',
          align: 'center',
          hideInSearch: true,
          valueType: 'index',
          render: (dom, record, index) => {
            const pageInfo = actionRef.current?.queryParams();
            return ((pageInfo?.current || 1) - 1) * (pageInfo?.pageSize || 0) + (index + 1);
          },
        },
        {
          title: '封面',
          dataIndex: nameof<Entity>((x) => x.journalCoverPathUrl),
          width: 120,
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
          align: 'center',
          valueType: 'image',
          fieldProps: {
            width: 75,
            height: 106,
            fallback: defaultPlaceHolderImg,
          },
        },
        {
          title: '名称',
          dataIndex: nameof<Entity>((x) => x.journalNameCn),
          sorter: false,
          hideInSearch: true,
          ellipsis: false,
        },
        {
          title: '语种',
          dataIndex: nameof<Entity>((x) => x.languageType),
          width: 80,
          align: 'center',
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
          show: false,
          kfValueEnum: 'LanguageType',
        },
        {
          title: '出版周期',
          dataIndex: nameof<Entity>((x) => x.journalPublicationCycle),
          width: 100,
          align: 'center',
          sorter: false,
          hideInSearch: false,
          ellipsis: true,
          kfValueEnum: 'JournalPublicationCycle',
        },
        {
          title: 'ISSN/eISSN',
          dataIndex: nameof<Entity>((x) => x.journalIssn),
          width: 200,
          align: 'center',
          sorter: false,
          hideInSearch: false,
          ellipsis: true,
          render: (_, record) => {
            let issn = (record.journalIssn || '').trim();
            let eissn = record.journalEissn;
            //2096-9384(eISSN 2524-4434), 从正则里面提取 issn和 eissn
            const regex = /^(\d{4}-\d{4})\(eISSN\s*(\d{4}-\d{4})\)$/g;
            if (regex.test(issn)) {
              let match = issn.match(/(\d{4}-\d{4})/g);
              if (match) {
                issn = match[0];
                eissn = match[1];
              }
            }
            return (
              <Space direction={'vertical'} className={'issn-eissn-wrap'}>
                <div className={'issn-item'}>{issn}</div>
                {eissn && <div className={'eissn-item'}>{eissn}</div>}
              </Space>
            );
          },
        },
        {
          title: '创建/更新',
          dataIndex: nameof<Entity>((x) => x.createTime),
          width: 200,
          align: 'center',
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
          render: (_, record) => {
            return (
              <Space direction={'vertical'}>
                <div>
                  <RocketOutlined /> {record.createTime}
                </div>
                <div>
                  <EditOutlined /> {record.modifyTime}
                </div>
              </Space>
            );
          },
        },
        {
          title: '操作',
          fixed: 'right',
          width: 230,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <Space size={0} split={<Divider type="vertical" />}>
              {languageType === 'CN' && (
                <>
                  <Link to={`/journal/${record.id}/period`}>刊期</Link>
                  <Link to={`/journal/${record.id}/column`}>栏目</Link>
                </>
              )}
              <a
                onClick={() => {
                  actionRef.current?.openFloating.single?.modifyModal(record, 'modal');
                }}
              >
                编辑
              </a>
              {
                // 自己创建的允许删除(只要id长度8以上就视为自己创建的)
                record.id.toString().length > 8 && (
                <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                  <Typography.Text type="danger">删除</Typography.Text>
                </a>
              )}
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
